# -*- coding:utf-8 -*-
from django.db.models.fields.related import ForeignObjectRel

__author__ = 'Forcs'

from django.db import models
import wancake.config as wc_config

import datetime

'''
    测试模型
'''

class BaseModel(models.Model):

    class Meta:
        abstract = True
        app_label = wc_config.DATABASE

    def from_json(self, json_data, epg_id_column_name='id'):
        for (name, value) in json_data.items():
            if name == epg_id_column_name:
                name = 'epg_id'

            try:
                field_tuple = self._meta.get_field_by_name(name)
                field = field_tuple[0]
                if isinstance(field, models.DateTimeField):
                    try:
                        setattr(self, field.name, datetime.datetime.strptime(
                            value, '%Y-%m-%d %H:%M:%S') if value is not None else None)
                    except Exception as e:
                        setattr(self, field.name, datetime.datetime.strptime(
                            value, '%Y-%m-%dT%H:%M:%S.%fZ') if value is not None else None)

                elif isinstance(field, models.DateField):
                    setattr(self, field.name, datetime.datetime.strptime(
                        value, '%Y-%m-%d') if value is not None else None)
                elif hasattr(field, "from_json") and callable(getattr(field, "from_json", None)):
                    setattr(self, field.name, field.from_json(value))
                else:
                    if name == epg_id_column_name:
                        setattr(self, "epg_id", value)
                    else:
                        setattr(self, field.name, value)
            except:
                pass

    def to_json(self, raw_id_column_name='id', include_id=True):
        fields = self._meta.get_fields()
        json = dict()
        for field in fields:
            if isinstance(field, ForeignObjectRel):
                continue

            val = getattr(self, field.name)
            if isinstance(val, datetime.datetime):
                try:
                    json[field.name] = val.strftime('%Y-%m-%d %H:%M:%S')
                except Exception, e:
                    json[field.name] = val.strftime('%Y-%m-%dT%H:%M:%S.%fZ')

            elif isinstance(val, datetime.date):
                json[field.name] = val.strftime('%Y-%m-%d')
            elif hasattr(val, "to_json") and callable(getattr(val, "to_json", None)):
                json[field.name] = val.to_json(raw_id_column_name='', include_id=True)
            else:
                if field.name == 'epg_id':
                    json[raw_id_column_name] = val
                elif field.name == 'id':
                    if include_id:
                        if raw_id_column_name == field.name:
                            json['_id'] = val
                        else:
                            json[field.name] = val
                else:
                    json[field.name] = val

        return json


'''
    配置项模型
'''


class Settings(BaseModel):
    """
    用于存储系统配置项信息
    """
    name = models.CharField(max_length=64)  # 配置项的名称
    value = models.CharField(max_length=256)  # 配置项的值，都是字符型

    def __str__(self):
        self.__unicode__()

    def __unicode__(self):
        return u'name: %s, value: %s' % (self.name, self.value)


'''
    用户模型
'''
class User(BaseModel):
    """
    用于存放用户数据
    """
    username = models.CharField(max_length=30)  # 用户名
    password = models.CharField(max_length=256)  # 密码
    email = models.EmailField()  # 邮箱
    session_id = models.BigIntegerField(default=-1)  # session id
    group = models.IntegerField(default=0)  # 分组
    permission = models.IntegerField(default=0)  # 权限
    date_added = models.DateTimeField(null=True)  # 加入的时间
    date_last = models.DateTimeField(null=True)  # 最近一次登录的时间
    is_super = models.BooleanField(default=False)  # 是否是超级管理员
    is_active = models.BooleanField(default=False)  # 是否在线
    uuid = models.UUIDField(null=True)  # 唯一标识
    first_name = models.CharField(max_length=30, null=True)  # 姓
    last_name = models.CharField(max_length=30, null=True)  # 名
    is_invalid = models.BooleanField(default=False)  # 是否已删除

    def __str__(self):
        self.__str__()

    def __unicode__(self):
        return u'username:%s, password:%s, email:%s' \
               % (self.username, self.password, self.email)


'''
    栏目模型
'''
class Category(BaseModel):
    """
    用于存放栏目信息
    """
    name = models.CharField(max_length=64)  # 栏目名称
    action = models.CharField(max_length=256)  # 栏目跳转uri
    type = models.IntegerField()  # 栏目类型标识
    icon = models.CharField(max_length=256)  # 栏目图标
    limits = models.IntegerField()  # 栏目权限位

    def __str__(self):
        self.__unicode__()

    def __unicode__(self):
        return u'name:%s, action:%s, type:%d, icon:%s' % (self.name, self.action, self.type, self.icon)


'''
    首页订购业务数据模型
'''
class OrderBusinessStatistics(BaseModel):
    """
    用于存放订购的业务
    """
    pv_hd = models.IntegerField(null=True)  # 高清访问量
    users_hd = models.IntegerField(null=True)  # 高清用户量
    new_series_hd = models.IntegerField(null=True)  # 高清新增订购量
    vods_hd = models.IntegerField(null=True)  # 高清点播量
    orders_month_hd = models.IntegerField(null=True)  # 高清包月数量
    orders_hd = models.IntegerField(null=True)  # 高清单点数量

    pv_sd = models.IntegerField(null=True)  # 标清访问量
    users_sd = models.IntegerField(null=True)  # 标清用户量
    new_series_sd = models.IntegerField(null=True)  # 标清新增订购量
    vods_sd = models.IntegerField()  # 标清点播量
    orders_month_sd = models.IntegerField(null=True)  # 标清包月数量
    orders_sd = models.IntegerField(null=True)  # 标清单点数量

    datetime = models.DateField(auto_now_add=True, null=True)  #日期

    def __str__(self):
        self.__unicode__()

    def __unicode__(self):
        return ''

'''
    订购用户模型
'''
class OrderUser(BaseModel):
    """
    用于存放订购用户信息
    """
    bid = models.CharField(max_length=64, null=False)  # 业务号
    name = models.CharField(max_length=64)  # 名称
    orders = models.IntegerField()  # 订购产品数量
    vods = models.IntegerField()  # 点播时长
    date_added = models.DateTimeField()  # 开户时间
    date_last = models.DateTimeField()  # 最近访问时间
    state = models.PositiveSmallIntegerField()  # 用户当前状态
    sp_id = models.IntegerField(null=False)  # SP标记

'''
    产品模型
'''
class Product(BaseModel):
    """
    用于存放产品信息
    """
    code = models.CharField(max_length=128, null=False)  # 产品码
    name = models.CharField(max_length=64)  # 产品名称
    category = models.PositiveSmallIntegerField()  # 产品归类
    sp_id = models.IntegerField(null=False)  # SP标记
    date_added = models.DateTimeField()  # 产品添加时间

    def __str__(self):
        self.__unicode__()

    def __unicode__(self):
        print u'name:%s, code:%s, category:%d' % (self.name, self.code, self.category)

'''
    订购模型
'''
class OrderHistory(BaseModel):
    """
    用于存放订购记录
    """
    user_bid = models.CharField(max_length=64, null=False)  # 用户的业务号
    product_name = models.CharField(max_length=64)  # 产品名称
    date_added = models.DateTimeField()  # 订购时间
    state = models.PositiveSmallIntegerField()  # 订购状态
    date_off = models.DateTimeField(null=True)  # 退订时间
    platform = models.IntegerField()  # 平台
    cp_permission = models.CharField(max_length=256, null=True)  # CP权限标记

'''
    摘要模型
'''
class Digest(BaseModel):

    orders = models.IntegerField(null=True)  # 总订购量
    users = models.IntegerField(null=True)  # 总用户数
    pv = models.IntegerField(null=True)  # 总访问量
    contents = models.IntegerField(null=True)  # 总内容数
    durations = models.BigIntegerField(null=True)  # 总播放时长

    # o 4365 u 807644 p 2725293 c 31872  d 161201500

'''
    产品详情总表
'''
class AppDetailsTotal(BaseModel):
    """
    用于存放产品详情总览表，hd:高清, sd:标清
    """
    product_id = models.CharField(max_length=256, null=True)    # 产品id
    product_name = models.CharField(max_length=256, null=True)    # 产品名称
    pv_hd = models.PositiveIntegerField(null=True, default=0)    # 访问量
    pv_sd = models.PositiveIntegerField(null=True, default=0)
    users_hd = models.PositiveIntegerField(null=True, default=0)    # 用户量
    users_sd = models.PositiveIntegerField(null=True, default=0)
    orders_hd = models.PositiveIntegerField(null=True, default=0)    # 订购量
    orders_sd = models.PositiveIntegerField(null=True, default=0)
    contents_hd = models.PositiveIntegerField(null=True, default=0)    # 内容数量
    contents_sd = models.PositiveIntegerField(null=True, default=0)
    durations_hd = models.PositiveIntegerField(null=True, default=0)    # 播放时长
    durations_sd = models.PositiveIntegerField(null=True, default=0)
    plays_hd = models.PositiveIntegerField(null=True, default=0)    # 播放次数
    plays_sd = models.PositiveIntegerField(null=True, default=0)
    week_act_hd = models.PositiveIntegerField(null=True, default=0)    # 周活跃度
    week_act_sd = models.PositiveIntegerField(null=True, default=0)
    day_act_hd = models.PositiveIntegerField(null=True, default=0)    # 日活跃度
    day_act_sd = models.PositiveIntegerField(null=True, default=0)
    cp_permission = models.CharField(max_length=256, null=True)    # cp权限位

'''
    应用与栏目关联表
'''
class AppCategoryRelate(BaseModel):
    """
    用于存放应用和栏目的对应关系，一对多
    """
    app_code = models.CharField(max_length=256, null=True)    # 应用码
    category_code = models.CharField(max_length=256, null=True)    # 栏目编码


'''
    应用与产品包关联表
'''
class AppProductRelate(BaseModel):
    """
    用于存放应用和产品包的对应关系，一对多
    """
    app_code = models.CharField(max_length=256, null=True)    # 应用码
    product_code = models.CharField(max_length=256, null=True)    # 产品包码


'''
    应用信息表
'''
class ApplicationInfo(BaseModel):
    """
    用于存放应用基本信息
    """
    code = models.CharField(max_length=10, null=True)  # 应用码
    name = models.CharField(max_length=32, null=True)  # 应用名称
    package = models.CharField(max_length=128, unique=True, null=True)  # 应用包名
    date_added = models.DateTimeField(null=True)  # 创建时间
    app_key = models.CharField(max_length=32, null=True)  # appkey
    secret_key = models.CharField(max_length=64, null=True)  # 安全秘钥


class StbUser(BaseModel):
    """
    存放机顶盒用户信息
    """
    user_id = models.CharField(max_length=256, null=True)  # 用户id
    stb_sn = models.CharField(max_length=256, null=True)  # 机顶盒序列号
    stb_name = models.CharField(max_length=256, null=True)  # 机顶盒设备名称
    stb_id = models.CharField(max_length=256, null=True)  # 机顶盒设备id
    datetime_added = models.DateTimeField(null=True)  # 加入时间
    datetime_last = models.DateTimeField(null=True)  # 最近时间
    flavor = models.CharField(max_length=64, null=True)  # 渠道/驻地
    platform = models.PositiveSmallIntegerField(null=True)  # 平台（1：高清，其他：标签）


class WanbaProductCategory(BaseModel):
    product_code = models.CharField(max_length=256, null=True)
    cate_code = models.CharField(max_length=32, null=True)

